package com.java.simple.study.juc.p5;

import com.java.simple.study.tool.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicMarkableReference;

/**
 * @author zhoujunlin
 * @date 2022年07月01日 21:45
 * @desc
 */
@Slf4j(topic = "c.ABAStampedRef")
public class ABAMarkableRef {


    public static void main(String[] args) {
        GarbageBag bag = new GarbageBag("装满了垃圾");
        // TRUE  装满了垃圾
        AtomicMarkableReference<GarbageBag> ref = new AtomicMarkableReference<>(bag, Boolean.TRUE);

        log.debug("主线程start...");
        // 此时 mainPrev == bag
        GarbageBag mainPrev = ref.getReference();
        log.debug(mainPrev.toString());

        /*new Thread(() -> {
            // 满垃圾袋->空垃圾袋  成功为止
            log.debug("打扫卫生线程start...");
            bag.setDesc("空垃圾袋");
            while (!ref.compareAndSet(ref.getReference(), bag, Boolean.TRUE, Boolean.FALSE)) {
            }
            log.debug(bag.toString());
        }, "打扫卫生线程").start();*/

        Sleeper.sleep(1);
        log.debug("主线程想换一只新垃圾袋");
        // 此时已经是空垃圾袋了  mainPrev:空垃圾袋
        boolean success = ref.compareAndSet(mainPrev, new GarbageBag("空垃圾袋"), Boolean.TRUE, Boolean.FALSE);
        log.debug("换了么？" + success);
        log.debug(ref.getReference().toString());

    }

}

class GarbageBag {
    String desc;

    public GarbageBag(String desc) {
        this.desc = desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    @Override
    public String toString() {
        return "GarbageBag{" +
                "desc='" + desc + '\'' +
                '}';
    }
}

